<template>
  <view class="picGroup">
    <view :style="{ width: width + 'px', aspectRatio: ratio }" class="box add" v-if="!formData.tempurl" @click="selectPic">
      <uni-icons type="plusempty" size="30" color="#999"></uni-icons>
    </view>
    <view :style="{ width: width + 'px', aspectRatio: ratio }" class="box pic" v-else>
      <image :src="formData.tempurl" mode="aspectFit"></image>
      <view class="mask">
        <view class="icon" @click="editPic">
          <uni-icons type="compose" size="20" color="#fff"></uni-icons>
        </view>
        <view class="icon" @click="deletePic">
          <uni-icons type="trash" size="20" color="#fff"></uni-icons>
        </view>
      </view>
    </view>
  </view>
  <cropper-image
    ref="cropperImageRef"
    :src="formData.tempurl"
    @save="handleSavePic"
    :maxImgSize="1200"
  />
</template>

<script setup>
import { ref } from 'vue';
import cropperImage from '@/components/cropper-image/cropper-image.vue';
const props = defineProps({
  formData: {
    type: Object,
    required: true,
  },
  width: {
    type: Number,
    default: 200,
  },
  ratio: {
    type: String,
    default: '16 / 9',
  },
});

const emit = defineEmits(['update:formData']);
const cropperImageRef = ref(null);
const selectPic = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['original'],
    success: (res) => {
      emit('update:formData', {
        ...props.formData,
        tempurl: res.tempFilePaths[0],
      });
    },
  });
};
const deletePic = () => {
  emit('update:formData', { ...props.formData, tempurl: '', picurl: '' }); 
};
const editPic = () => {
  cropperImageRef.value.open();
};
const handleSavePic = (url) => {
  emit('update:formData', { ...props.formData, tempurl: url });
};
</script>

<style scoped lang="scss">
.picGroup {
  .box {
    //width: 200px;
    //aspect-ratio: 16/9;
    border: 1px solid #e4e4e4;
    border-radius: 5px;
    overflow: hidden;
  }
  .add {
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
  }
  .pic {
    position: relative;
    background: conic-gradient(
      #ccc 0 25%,
      #fff 25% 50%,
      #ccc 50% 75%,
      #fff 75% 100%
    );
    background-size: 10px 10px;
    image {
      width: 100%;
      height: 100%;
    }
    .mask {
      background-color: rgba(0, 0, 0, 0.4);
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .icon {
        border-radius: 50%;
        flex: 1;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
      }
    }
  }
}
</style>
